#
# create by dplord at 2016-07-03 03:06
#
require 'nokogiri'
require 'net/http'
require 'uri'
require 'fileutils'



dirName = ARGV[1]
dirName = '/home/dengpan/下载/张皎/' + dirName + '/'
if Dir.exist?(dirName) == true
  FileUtils.rm_rf(dirName)
end

def getHtml(url)
  url = URI.parse(url)
  http = Net::HTTP.new(url.host, url.port)

  headers = {
      'Referer' => 'http://photo.renren.com/photo/260782071/album-836092379/v7#nogo',
      'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
      'Host' => 'photo.renren.com',
      'Cookie' => '', 
  }

  resp = http.get(url, headers)

  return resp
end

def getLargeUrl(imgUrl)
  @begin = imgUrl.index '/p/'
  @str = imgUrl[0..@begin]
  @str1 = imgUrl[(@begin + 3)..(imgUrl.length)]

  if imgUrl.include? 'large'
    @begin = @str1.index 'large'
  end
  if imgUrl.include? 'original'
    @begin = @str1.index 'original'
  end
  return @str + @str1[@begin..@str1.length]
end

html = open(ARGV[0]).read()

# html = open('/tmp/1.html').read()
html = Nokogiri::HTML(html)


html.css('div#photo-list img').each {|d|
  p d['src']
  if d['src'].include? 'jpg'

  imgUrl = getLargeUrl(d['src'])
  p imgUrl
  p d['src']
  @begin = imgUrl.rindex('/')
  fname = imgUrl[(@begin+1)..(imgUrl.length)]




  dirName = ARGV[1]
  dirName = '/home/dengpan/下载/张皎/' + dirName + '/'
  if Dir.exist?(dirName) == false
    Dir.mkdir(dirName)
  end


  # system("cd #{dirName} && wget #{d['src']}")
  fname = dirName + fname
  if File.exist? fname
    @begin = fname.rindex '.'
    fname = fname[0..(@begin-1)] + Time.now.strftime('-%Y-%m-%d-%H_%M_%S') + fname[@begin, fname.length]
  end
  p fname



  url = URI.parse(imgUrl)
  http = Net::HTTP.new(url.host, url.port)

  headers = {
      'Referer' => 'http://photo.renren.com/photo/260782071/album-836092379/v7#nogo',
      'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
  }

  resp = http.get(url, headers)
  open(fname ,"wb") { |file|
    file.write(resp.body)
  }


  else

    100.times do
      p '#######################################'
    end
    p d['src']
    100.times do
      p '#######################################'
    end
  end
}

